<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 添加角色表格区域 -->
      <el-table :data="rolesList" border style="width: 100%;">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="['bdbottom', i1 === 0 ? 'bdbottom' : '', 'vcenter']"
            >
              <!-- 一级权限渲染 -->
              <el-col :span="5">
                <el-tag>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限渲染 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                >
                  <el-col :span="6">
                    <el-tag type="success">{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
                    {{ scope.row }}
            </pre> -->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              @close="setRightDialogClosed"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框区域 -->
    <el-dialog
      title="分配权限对话框"
      :visible.sync="setRightDialogVisible"
      width="30%"
    >
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      setRightDialogVisible: false,
      // 所有权限列表数据
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      defKeys: [],
      roleId: '',
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('获取用户角色信息失败！');
      }
      this.rolesList = res.data;
      // console.log(this.rolesList);
    },
    async removeRightsById(role, rightsid) {
      const result = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => {
        return err;
      });
      if (result !== 'confirm') {
        return this.$Elementui.Message.error('你已经取消了删除操作！');
      }
      // console.log(result);
      // console.log(rows);
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightsid}`
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('删除角色权限失败！');
      }
      // 删除权限的时候，用后台返回过来的最新的权限数据直接赋值给role.children,这样可以避免导致删除权限的时候导致页面被折叠。
      role.children = res.data;
      this.$Elementui.Message.success('删除角色权限成功！');
    },
    // 显示分配权限对话框
    async showSetRightDialog(roles) {
      // 弹出对话框的时候获取角色的id 并且将id保存起来
      this.roleId = roles.id;
      const { data: res } = await this.$http.get('rights/tree');
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('获取所有权限列表数据失败！');
      }
      // 保存获取的权限列表数据
      this.rightsList = res.data;
      // 调用递归函数
      this.getLeafKeys(roles, this.defKeys);
      this.setRightDialogVisible = true;
      console.log(this.rightsList);
    },
    // 定义一个递归函数获取所有三级子节点的id值
    getLeafKeys(node, arr) {
      // 如果当前节点中没有children数组或者children数组中为空，则表示它为三级节点,此时就要把三级节点里面的id值追加到arr中
      if (!node.children || node.children === []) {
        return arr.push(node.id);
      }
      // 否则利用递归函数来找寻所有的三级节点
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    // 每次关闭对话框的时候，清空一下保存三级权限的id的数组，防止每点击一次就defKeys里面添加一个id，导致其他本不具备三级权限的也具有了三级权限。
    setRightDialogClosed() {
      this.defKeys = [];
    },
    // 定义分配权限的方法
    async allotRights() {
      // 获取当前全选和半选状态下的子节点的id值
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // console.log(keys);
      // 将这个id 数组用逗号拼接成一个字符串
      const idStr = keys.join(',');
      // console.log(idStr);
      // 发起请求来分配权限
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) {
        return this.$Elementui.Message.error('分配用户权限失败！');
      }
      // 渲染页面
      this.getRolesList();
      // 关闭对话框
      this.setRightDialogVisible = false;
      // 提示用户分配权限成功
      this.$Elementui.Message.success('分配权限成功！');
    },
  },
};
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
}
.el-button {
  margin-bottom: 15px;
}
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
